package com.ok.common.common

import android.app.Activity
import android.app.Application
import android.os.Bundle

class ActivityLifecycleCallback : Application.ActivityLifecycleCallbacks {

    //运行的Activity个数
    private var liveActivityCount = 0

    //是否处于压后台状态
    private var mIsOnBackground = false

    //压后台的回调
    private var mOnBackgroundCallback: OnBackgroundCallback? = null

    /**
     * 是否处在压后台
     */
    fun isOnBackground(): Boolean {
        return mIsOnBackground
    }

    /**
     * 压后台的回调处理
     */
    interface OnBackgroundCallback {
        //压后台时触发
        fun handleOnBackground(activity: Activity?)

        //从后台回到前台时触发
        fun handleOnForeground(activity: Activity?)
    }

    /**
     * 设置压后台的回调处理
     * @param aCallback 回调
     */
    fun setOnBackgroundCallback(aCallback: OnBackgroundCallback?) {
        mOnBackgroundCallback = aCallback
    }

    /**
     * 运行Activity个数
     */
    fun getLiveActivityCount(): Int {
        return liveActivityCount
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
    }

    override fun onActivityStarted(activity: Activity) {
        liveActivityCount++
        if (mIsOnBackground) { //从压后台回来
            mOnBackgroundCallback?.handleOnForeground(activity)
            //重置后台标识
            mIsOnBackground = false
        }
    }

    override fun onActivityResumed(activity: Activity) {
    }

    override fun onActivityPaused(p0: Activity) {}

    override fun onActivityStopped(p0: Activity) {
        liveActivityCount--
        if (liveActivityCount == 0) {//处于后台
            mOnBackgroundCallback?.handleOnBackground(p0)
            mIsOnBackground = true
        }
    }

    override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {
        mIsOnBackground = false
    }

}